package com.zone.vehicle.superapp.view.appmanager.tab;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zone.lib.download.db.entity.Download;
import com.zone.lib.download.enums.AppStatusEnum;
import com.zone.lib.download.enums.AppTypeEnum;
import com.zone.sdk.common.http.base.Result;
import com.zone.vehicle.lib.view.textview.ExpandableTextView;
import com.zone.vehicle.lib.view.utils.ImageUtil;
import com.zone.vehicle.sdk.module.superapp.entity.AppUpdateEntity;
import com.zone.vehicle.superapp.R;
import com.zone.vehicle.superapp.bean.AppBean;
import com.zone.vehicle.superapp.databinding.FragmentAppManagerUpdateBinding;
import com.zone.vehicle.superapp.databinding.FragmentAppManagerUpdateItemBinding;
import com.zone.vehicle.superapp.model.AppManagerViewModel;
import com.zone.vehicle.superapp.model.ViewModelFactory;
import com.zone.vehicle.superapp.view.common.base.BaseFragment;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A fragment representing a list of Items.
 */
public class AppUpdateListFragment extends BaseFragment {

    private FragmentAppManagerUpdateBinding binding;

    private UpdateAppAdapter updateAppAdapter;

    private static AppManagerViewModel viewModel;

    private static Map<String, DownloadListener> downloadListeners = new HashMap<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentAppManagerUpdateBinding.inflate(inflater);
        viewModel = new ViewModelProvider(requireActivity(), new ViewModelFactory()).get(AppManagerViewModel.class);
        initView();
        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    private void initData(){
        downloadListeners.clear();
        viewModel.getNeedUpdateApps(getContext());
    }

    private void initView(){
        updateAppAdapter = new UpdateAppAdapter(new ArrayList<>());
        binding.updateList.setAdapter(updateAppAdapter);
        binding.updateList.getItemAnimator().setChangeDuration(0);
        binding.updateList.setLayoutManager(new GridLayoutManager(getContext(), 1));
        viewModel.getError().observe(getViewLifecycleOwner(), new Observer<Result>() {
            @Override
            public void onChanged(Result result) {
                if (ObjectUtils.isNotEmpty(result) && StringUtils.isNotEmpty(result.getResultMsg())) {
                    showLoginFailed(result.getResultMsg());
                }
            }
        });
        viewModel.getNeedUpdateApps().observe(getViewLifecycleOwner(), new Observer<List<AppBean>>() {
            @Override
            public void onChanged(List<AppBean> appBeans) {
                updateAppAdapter.setData(appBeans);
                updateAppAdapter.notifyDataSetChanged();
            }
        });
        setHandler(handler);
    }

    private static class UpdateAppAdapter extends RecyclerView.Adapter<UpdateAppAdapter.ViewHolder>{

        private List<AppBean> data;

        private FragmentAppManagerUpdateItemBinding binding;

        public UpdateAppAdapter(List<AppBean> data) {
            this.data = data;
        }

        public void setData(List<AppBean> data) {
            this.data = data;
        }

        @NotNull
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            binding = FragmentAppManagerUpdateItemBinding.inflate(LayoutInflater.from(parent.getContext()));
            return new ViewHolder(binding.getRoot());
        }

        @Override
        public void onBindViewHolder(@NotNull ViewHolder holder, int position) {
            if (ObjectUtils.isEmpty(data)){
                return;
            }
            AppBean appBean = data.get(position);
            Download download = appBean.getDownload();
            holder.name.setText(appBean.getName());
            AppUpdateEntity updateEntity = appBean.getUpdateEntity();
            if (ObjectUtils.isNotEmpty(updateEntity)){
                String version = "";
                if (StringUtils.isNotEmpty(updateEntity.getNewVersion())){
                    version = updateEntity.getNewVersion() + " . ";
                }
                if (StringUtils.isNotEmpty(updateEntity.getSize())){
                    version += updateEntity.getSize();
                }
                holder.version.setText(version);
            }

            holder.desc.setText(appBean.getDescription());
            holder.desc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean b = ((ExpandableTextView)v).getExpandableStatus();
                    ((ExpandableTextView)v).setExpandable(!b);
                }
            });
            holder.showMore.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean b = ((ExpandableTextView)v).getExpandableStatus();
                    ((ExpandableTextView)v).setExpandable(!b);
                }
            });
            ImageUtil.load(holder.itemView.getContext(), holder.icon, appBean.getIconUrl());
            holder.download_progress.setTag(R.id.tag_first, download.getCode());
            DownloadListener downloadListener = new DownloadListener() {
                @Override
                public void onDownloading(Download download) {
                    String code = (String)holder.download_progress.getTag(R.id.tag_first);
                    if (download.getCode().equals(code)) {
                        holder.download_progress.setProgress((int) (download.getDownloadLocation() * 100 / download.getTotal()));
                        holder.btn_activity.setBackgroundColor(Color.TRANSPARENT);
                    }
                }
            };
            downloadListeners.put(download.getCode(), downloadListener);
            switch (AppStatusEnum.get(download.getDownloadStatus())) {
                case DOWNLOAD_LOADING:
                    holder.btn_activity.setVisibility(View.GONE);
                    holder.download_progress.setVisibility(View.VISIBLE);
                    holder.download_progress.setProgress((int) (download.getDownloadLocation() * 100 / download.getTotal()));
                    break;
                case INSTALL_SUCCESS:
                case LIGHT_INSTALL_COMPLETE:
                    holder.btn_activity.setVisibility(View.VISIBLE);
                    holder.btn_activity.setText("更新");
                    break;
                default:
                    holder.download_progress.setProgress(0);
                    holder.download_progress.setVisibility(View.GONE);
                    holder.btn_activity.setVisibility(View.VISIBLE);
                    holder.btn_activity.setText(AppStatusEnum.get(download.getDownloadStatus()) != null ? AppStatusEnum.get(download.getDownloadStatus()).TITLE : null);
                    break;
            }
            holder.btn_activity.setTag(position);
            holder.btn_activity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int p = (int) v.getTag();
                    AppBean b = data.get(p);
                    if (null == b) {
                        Log.e(TAG, "error click of null data");
                        return;
                    }
                    Download d = b.getDownload();
                    if (null == d || AppStatusEnum.get(d.getDownloadStatus()) == null) {
                        Log.e(TAG, "error click download of null download data");
                        return;
                    }
                    switch (AppStatusEnum.get(d.getDownloadStatus())) {
                        case INSTALL_SUCCESS:
                        case LIGHT_INSTALL_COMPLETE:
                            viewModel.updateApp(v.getContext(), AppStatusEnum.DOWNLOAD_PREPARE, b);
                            break;
                        case DOWNLOAD_DEFAULT:
                        case DOWNLOAD_DEFAULT_LIGHT:
                        case DOWNLOAD_PAUSE:
                        case DOWNLOAD_FAIL:
                        case LIGHT_INSTALL_FAIL:
                            viewModel.downLoadApp(v.getContext(), AppStatusEnum.DOWNLOAD_PREPARE, b);
                            break;
                        case DOWNLOAD_PREPARE:
                        case DOWNLOAD_LOADING:
                            viewModel.downLoadApp(v.getContext(), AppStatusEnum.DOWNLOAD_PAUSE, b);
                            break;
                        case INSTALL_FAIL:
                            viewModel.install(v.getContext(), AppStatusEnum.INSTALL_PREPARE, b);
                            break;
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {

            private final ImageView icon;
            private final TextView name;
            private final ProgressBar download_progress;
            private final AppCompatButton btn_activity;
            private final AppCompatTextView version;
            private final ExpandableTextView desc;
            private final AppCompatImageView showMore;

            public ViewHolder(View itemView) {
                super(itemView);
                icon = itemView.findViewById(R.id.icon);
                name = itemView.findViewById(R.id.name);
                download_progress = itemView.findViewById(R.id.download_progress);
                btn_activity = itemView.findViewById(R.id.btn_activity);
                version = itemView.findViewById(R.id.version);
                desc = itemView.findViewById(R.id.desc);
                showMore = itemView.findViewById(R.id.showMore);
            }
        }
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {

            switch (msg.what){
                case 1:
                    Download download = (Download)msg.obj;
                    if (download.getDownloadStatus() == AppStatusEnum.INSTALL_SUCCESS.CODE || download.getDownloadStatus() == AppStatusEnum.UNINSTALL_APP_SUCCESS.CODE){
                        viewModel.getInstallApps(requireContext(), AppTypeEnum.APP);
                    }else if (download.getDownloadStatus() == AppStatusEnum.DOWNLOAD_LOADING.CODE){
                        notifyDownload(download);
                    }
//                    if (ObjectUtils.isNotEmpty(download) && download.getAppType().equals(AppTypeEnum.APP.getName())){
//                        initData();
//                    }
            }
            return false;
        }
    });

    private void notifyDownload(Download download){
        if (downloadListeners.containsKey(download.getCode())){
            downloadListeners.get(download.getCode()).onDownloading(download);
        }
    }

    interface DownloadListener {
        void onDownloading(Download download);
    }

}